from playwright.sync_api import Page
from core.model import ElementModel
import allure

class KeyboardKeywords:
    def __init__(self, page: Page):
        self.page = page

    def type_text(self, element_model: ElementModel, text: str, time_out=12):
        """
        模拟键盘输入文本
        :param element_model: 元素模型
        :param text: 要输入的文本
        """
        step_desc = "输入文本" if element_model.desc is None else f"在{element_model.desc}输入文本"
        with allure.step(step_desc):
            try:
                self.page.locator(element_model.selector).type(text, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功: {text}")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise

    def press_key(self, element_model: ElementModel, key: str, time_out=12):
        """
        按下单个按键
        :param element_model: 元素模型
        :param key: 按键名称(如'Enter', 'Tab'等)
        """
        step_desc = "按下按键" if element_model.desc is None else f"在{element_model.desc}按下{key}键"
        with allure.step(step_desc):
            try:
                self.page.locator(element_model.selector).press(key, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise

    def press_combination(self, keys: str, time_out=12):
        """
        按下组合键
        :param keys: 组合键字符串(如'Control+A')
        """
        step_desc = f"按下组合键: {keys}"
        with allure.step(step_desc):
            try:
                self.page.keyboard.press(keys, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise